package org.jianfa.learn.rabbitmqdeadletter.controller;

import com.fasterxml.jackson.databind.util.JSONPObject;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 基于RabbitMQ的TTL以及死信队列，使用SpringBoot实现延迟付款，手动补偿操作。
 *
 * 1、用户下单后展示等待付款页面
 * 2、在页面上点击付款的按钮，如果不超时，则跳转到付款成功页面
 * 3、如果超时，则跳转到用户历史账单中查看因付款超时而取消的订单。
 */
@Controller
public class OrderController {

    @Autowired
    private AmqpTemplate rabbitTemplate;

    private ConcurrentMap<String, Boolean> concurrentMap = new ConcurrentHashMap<String, Boolean>();

    @GetMapping("/")
    public String index() {
        return "index";
    }

    @GetMapping("/result")
    public  String result(@RequestParam("orderId") String orderId, Model model) {
        if (concurrentMap.containsKey(orderId)) {
            Boolean aBoolean = concurrentMap.get(orderId);

            if (aBoolean) {
                model.addAttribute("message", "支付成功");
            } else {
                model.addAttribute("message", "支付失败");
            }

        } else {
            model.addAttribute("message", "查无订单。");
        }
        return "result";
    }

    @PostMapping("/check")
    @ResponseBody
    public String check(@RequestParam("orderId") String orderId) {
        rabbitTemplate.convertAndSend("ex.go", "go", orderId);
        return "OK";
    }

//    @RabbitListener(queues = "q.go")
//    public void receiveFromNormalQueue(String message) {
//        System.out.println("普通队列消息: " + message);
//        concurrentMap.put(message, true);
//    }

    @RabbitListener(queues = "q.go.dlx")
    public void receiveFromDeadLetterQueue(String message) {
        System.out.println("死信队列消息: " + message);
        concurrentMap.put(message, false);
    }
}
